package poketrade;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import poketrade.entities.Carte;
import poketrade.entities.subtypes.InvalidCardIndex;
import poketrade.managers.CardsManager;

/**
 * Servlet implementation class CardImageServlet
 */
public class CardImageServlet extends BaseHttpServlet {
	private static final long serialVersionUID = 1L;
	
	@EJB
	private CardsManager mgr;
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String cardIndex = request.getParameter("n");
		if (cardIndex == null || !Carte.hasValidFormat(cardIndex))
		{
			cardIndex = (String) request.getAttribute("n");
			if (cardIndex == null)
			{
				returnError(request, response, HttpServletResponse.SC_PRECONDITION_FAILED);
				return;
			}
		}
		
		
		Carte c = mgr.getCardById(cardIndex);
		if (c == null)
		{
			returnError(request, response, HttpServletResponse.SC_NO_CONTENT);
			return;
		}
		
		byte [] imageContent = c.getImage();
		
		response.setContentLength(imageContent.length);
		OutputStream os = response.getOutputStream();
		os.write(imageContent);
	}
	
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String referenceCarte = null, nomCarte = null, descriptionCarte = null;
		byte [] imageCarte = null;
		
		if (!ServletFileUpload.isMultipartContent(request))
		{
			returnError(request, response, HttpServletResponse.SC_PRECONDITION_FAILED);
			return;
		}
		
		DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
		fileItemFactory.setSizeThreshold(5 * 1024 * 1024);
		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		List<FileItem> items = null;
		try {
			items = uploadHandler.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
			returnError(request, response, HttpServletResponse.SC_PRECONDITION_FAILED);
			return;
		}
		
		for (FileItem item : items)
		{
			if (item.isFormField())
			{
				if (item.getFieldName().equals("referenceCarte"))
					referenceCarte = item.getString();
				else if (item.getFieldName().equals("nomCarte"))
					nomCarte = item.getString();
				else if (item.getFieldName().equals("descriptionCarte"))
					descriptionCarte = item.getString();
			}
			else
				imageCarte = item.get();
		}
		
		if (referenceCarte != null && nomCarte != null && descriptionCarte != null && imageCarte != null)
		{
			Carte c = new Carte();
			try {
				c.setCardIndex(referenceCarte);
			} catch (InvalidCardIndex e) {
				showMessage(request, response, "Référence de carte invalide :(");
				return;
			}
			c.setNom(nomCarte);
			c.setDescription(descriptionCarte);
			c.setImage(imageCarte);
			if (mgr.registerCard(c) == null)
				showMessage(request, response, "Carte déjà existante ;)");
			else
				redirect(response, "posterAnnonce.jsp");
		}
	}

	private void returnError(HttpServletRequest request, HttpServletResponse response, int code) throws IOException
	{
		response.sendError(code);
	}
}
